'''
 * CaRComp Execution Environment
 * 
 * Copyright (C) 2011 Taylor L. Riche
 * 
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
'''

import re

FTCMD_PP = 'PP'
FTCMD_PREP = 'PREP'
FTCMD_COM = 'COM'
FTCMD_EXEC = 'EXEC'
FTCMD_CP = 'CP'
FTCMD_FETCH = 'FETCH'

class Message(object):
    
    def __init__(self, body=''):
        self.__body__ = body
        if body != '':
            self.parse_msg()
        
    def parse_msg(self, body=''):
        if body != '':
            self.__body__ = body
        m = re.search('(\S+);([0-9]+);([0-1])::(\S+\s*)', self.__body__)
        try:
            self.seq_no = int(m.group(2))
            self.cmd = m.group(1)
            self.internals = m.group(4)
            self.cp = int(m.group(3))
        except Exception as err:
            print('Illformed agreement msg: ' + self.__body__ + '(' + str(err) + ')')
            raise err
        return (self.seq_no, self.cmd, self.internals, self.cp)
    
    def create_msg_body(self, seq_no, cmd, internals, cp=0):
        self.seq_no = seq_no
        self.cmd = cmd
        self.internals = internals
        self.cp = cp
        self.__body__ = '{};{};{}::{}'.format(cmd,seq_no,cp,internals)
    
    def get_body(self):
        return self.__body__

class PPMsg(Message):
    
    def __init__(self, seq_no=0, internals=''):
        self.create_msg_body(seq_no, FTCMD_PP, internals)
        
class PrepMsg(Message):
    
    def __init__(self, seq_no=0, internals=''):
        self.create_msg_body(seq_no, FTCMD_PREP, internals)
        
class CommMsg(Message):
    
    def __init__(self, seq_no=0, internals='', cp=0):
        self.create_msg_body(seq_no, FTCMD_COM, internals, cp)
        
class ExecMsg(Message):
    
    def __init__(self, seq_no=0, internals='', cp=0):
        self.create_msg_body(seq_no, FTCMD_EXEC, internals, cp)
        
class CPMsg(Message):
    
    def __init__(self, seq_no=0, internals=''):
        self.create_msg_body(seq_no, FTCMD_CP, internals)

class FetchMsg(Message):
    
    def __init__(self, seq_no=0, internals=''):
        self.create_msg_body(seq_no, FTCMD_FETCH, internals)